<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    function addBigNumbers(num1Str, num2Str) {
      let i = num1Str.length - 1
      let j = num2Str.length - 1
      let carry = 0
      let result = ""

      // 循环直到两个字符串的指针都移到开头，并且没有进位为止
      while (i >= 0 || j >= 0 || carry > 0) {
        // 获取当前位的数字，如果指针<0，则该位数字为0
        const digit1 = i >= 0 ? parseInt(num1Str[i]) : 0
        const digit2 = j >= 0 ? parseInt(num2Str[j]) : 0

        // 计算当前位的和（包括上一位的进位）
        const currentSum = digit1 + digit2 + carry

        // 当前位的结果是和对10取余
        const currentDigit = currentSum % 10
        result = currentDigit + result // 将当前位数字加到结果字符串的前面

        // 计算新的进位
        carry = Math.floor(currentSum / 10)

        // 移动指针
        i--
        j--
      }

      return result
    }

    // --- 测试代码 ---
    // console.log(`"123" + "456" = ${addBigNumbers("123", "456")}`) // Expected: "579"
    console.log(`"99" + "9" = ${addBigNumbers("99", "9")}`) // Expected: "108"
    // console.log(`"1" + "999" = ${addBigNumbers("1", "999")}`) // Expected: "1000"
    // console.log(`"888" + "222" = ${addBigNumbers("888", "222")}`) // Expected: "1110"
    // console.log(`"0" + "0" = ${addBigNumbers("0", "0")}`) // Expected: "0"
    // console.log(
    //   `"12345678901234567890" + "1" = ${addBigNumbers(
    //     "12345678901234567890",
    //     "1"
    //   )}`
    // ) // Expected: "12345678901234567891"
    // console.log(
    //   `"99999999999999999999" + "1" = ${addBigNumbers(
    //     "99999999999999999999",
    //     "1"
    //   )}`
    // ) // Expected: "100000000000000000000"
  </script>
</html>
